<template>
	<view class="uric-acid-container">
		<!-- 最新尿酸 -->
		<view class="latest-uric-acid">
			<view class="section-header">
				<text>最新尿酸</text>
				<view class="view-more" style="z-index: 99;" @click="toMoreUricAcid">查看更多 ></view>
			</view>
			<view class="charts-box">
				<qiun-data-charts type="arcbar" :opts="opts" :chartData="chartData" canvas-id="uricAcidArc" />
			</view>
			<view class="measure-time" v-if="records.length>0">测量时间：{{records[0].measuredTime}} <span
					style="padding-left: 10px;" :style="{color: records[0].color}">{{ records[0].tag}}</span></view>
		</view>

		<!-- 尿酸趋势 -->
		<view class="uric-acid-trend">
			<view class="section-header">
				<text>尿酸趋势</text>
				<text class="view-more">查看详情 ></text>
			</view>
			<view class="date-filter">
				<view class="filter-buttons">
					<text :class="{ active: activeFilter === 'week7' }" @click="switchFilter('week7')">近七天</text>
					<text :class="{ active: activeFilter === 'day' }" @click="switchFilter('day')">日</text>
					<text :class="{ active: activeFilter === 'week' }" @click="switchFilter('week')">周</text>
					<text :class="{ active: activeFilter === 'month' }" @click="switchFilter('month')">月</text>
				</view>
				<view class="date-picker-range">
					<picker mode="date" :value="startDate" @change="onStartDateChange">
						<text>{{startDate}}</text>
					</picker>
					<text class="separator">至</text>
					<picker mode="date" :value="endDate" @change="onEndDateChange">
						<text>{{endDate}}</text>
					</picker>
				</view>
			</view>
			<view class="chart-container">
				<qiun-data-charts type="line" :opts="trendOpts" :chartData="trendChartData" />
			</view>
			<view class="legend">
				<view class="legend-item">
					<view class="legend-label">
						<view class="dot normal"></view>
						<text>正常</text>
					</view>
					<text class="count">{{statistics.normalCount}}次</text>
				</view>
				<view class="legend-item">
					<view class="legend-label">
						<view class="dot high"></view>
						<text>高尿酸</text>
					</view>
					<text class="count high">{{statistics.highCount}}次</text>
				</view>
			</view>
		</view>

		<!-- 尿酸对比 -->
		<!-- <view class="uric-acid-comparison">
			<view class="section-header">
				<text>尿酸对比</text>
			</view>
			<view class="comparison-tabs">
				<text :class="{ active: comparisonType === 'day' }" @click="switchComparisonType('day')">按天</text>
				<text :class="{ active: comparisonType === 'week' }" @click="switchComparisonType('week')">按周</text>
				<text :class="{ active: comparisonType === 'month' }" @click="switchComparisonType('month')">按月</text>
			</view>
			<view class="date-selection">
				<view class="date-item">
					<text>选择日期:</text>
					<picker mode="date" :value="selectedDate" @change="onSelectedDateChange">
						<text>{{selectedDate}} ></text>
					</picker>
				</view>
				<view class="date-item">
					<text>对比日期:</text>
					<picker mode="date" :value="compareDate" @change="onCompareDateChange">
						<text>{{compareDate}} ></text>
					</picker>
				</view>
			</view>
			<view class="comparison-result" v-if="comparisonData">
				<view class="result-item">
					<text>选择时间:{{comparisonData.selectedTime}} {{comparisonData.selectedValue}}μmol/L</text>
				</view>
				<view class="result-comparison">
					<text class="comparison-value" :class="comparisonData.diff > 0 ? 'up' : 'down'">
						{{comparisonData.diff > 0 ? '↑' : '↓'}}{{Math.abs(comparisonData.diff)}}
					</text>
				</view>
				<view class="result-item">
					<text>对比时间:{{comparisonData.compareTime}} {{comparisonData.compareValue}}μmol/L</text>
				</view>
			</view>
			<view class="comparison-chart" v-if="comparisonChartData">
				<qiun-data-charts type="line" :opts="comparisonOpts" :chartData="comparisonChartData" />
			</view>
		</view> -->

		<!-- 数据记录 -->
		<view class="data-records">
			<view class="section-header">
				<text>数据记录</text>
				<view class="view-more" @click="toMoreUricAcid">查看更多 ></view>
			</view>
			<view class="record-item" v-for="(item, index) in recentRecords" :key="index" v-if="recentRecords.length>0">
				<view class="record-main">
					<text class="value">尿酸：{{item.uricAcid}}μmol/L</text>
					<text>状态：<text :style="{color: item.color}">{{ item.tag}}</text></text>
				</view>
				<view class="record-sub">
					<text>上传方式：{{ item.sourceName }}</text>
				</view>
				<view class="record-time">测量时间：{{item.measuredTime}}</view>
			</view>
		</view>

		<!-- 免责声明 -->
		<view class="disclaimer">
			<text>注:以上数据仅供参考,不作为治疗及诊断依据;</text>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-button">
			<text class="bind-device">绑定设备</text>
			<button class="add-record" @click="addRecord">添加尿酸</button>
		</view>
	</view>
</template>

<script>
	import {
		addUricAcid,
		listUricAcid,
		queryTrendListUA,
		statisticsExceUA,
		queryUricAcidTypeList,
		queryUricAcidCompare
	} from '@/api/healthData/everyUricAcid.js'

	export default {
		data() {
			return {
				userId: this.$store.state.user.userId,
				records: [],
				dictsList: [],
				targetId: '',
				startDate: (() => {
					const date = new Date();
					date.setDate(date.getDate() - 6);
					return this.formatDate(date);
				})(),
				endDate: this.formatDate(new Date()),
				statistics: {
					normalCount: 0,
					highCount: 0
				},
				opts: {
					type: 'arcbar',
					canvasId: 'uricAcidArc',
					width: 180,
					height: 180,
					background: '#FFFFFF',
					animation: true,
					dataLabel: false,
					title: {
						name: "",
						color: '#333333',
						fontSize: 36,
						offsetY: -30
					},
					subtitle: {
						name: "μmol/L",
						color: '#999999',
						fontSize: 14,
						offsetY: -10
					},
					extra: {
						arcbar: {
							type: 'default',
							width: 12,
							backgroundColor: '#F5F5F5',
							startAngle: 0.8,
							endAngle: 0.2,
							gap: 2,
							linearType: 'none',
							roundCap: true
						}
					}
				},
				chartData: {
					series: [{
						name: "尿酸值",
						color: '#fb3f3f',
						data: 0.0
					}]
				},
				trendOpts: {
					color: ['#4cd8aa', '#ff4d4f', '#1890ff'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: false,
					xAxis: {
						disableGrid: true,
						fontSize: 12,
						color: '#666666'
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 4,
						data: [{
							min: 0,
							max: 1200,
							format: 'val'
						}]
					},
					extra: {
						line: {
							type: 'curve',
							width: 2,
							activeType: 'hollow'
						}
					}
				},
				trendChartData: {
					categories: [],
					series: [{
						name: "尿酸值",
						data: []
					}]
				},
				activeFilter: 'week7',
				comparisonType: 'day',
				selectedDate: this.formatDate(new Date()),
				compareDate: this.formatDate(new Date(Date.now() - 24 * 60 * 60 * 1000)),
				comparisonData: null,
				comparisonOpts: {
					color: ['#4cd8aa', '#ff9500'],
					canvasId: 'uricAcidComparison',
					width: 350,
					height: 200,
					background: '#FFFFFF',
					animation: true,
					dataLabel: false,
					dataPointShape: true,
					legend: {
						show: true,
						position: 'bottom'
					},
					xAxis: {
						disableGrid: false,
						itemCount: 7,
						scrollShow: true,
						scrollAlign: 'left'
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 2,
						data: [{
							min: 0,
							max: 1200
						}]
					},
					extra: {
						line: {
							type: 'curve',
							width: 2,
							activeType: 'hollow'
						}
					}
				},
				comparisonChartData: null
			}
		},
		computed: {
			recentRecords() {
				return this.records.slice(0, 2)
			}
		},
		onLoad(options) {
			this.targetId = options.targetId
			this.loadData()
		},
		onShow() {
			this.loadData()
		},
		methods: {
			// 格式化数值显示：保留一位小数，如果是整数则显示整数
			formatValue(value) {
				if (value === null || value === undefined || isNaN(value)) {
					return '0'
				}
				const num = parseFloat(value)
				// 如果是整数，直接返回整数
				if (num % 1 === 0) {
					return num.toString()
				}
				// 否则保留一位小数
				return num.toFixed(1)
			},
			
			loadData() {
				this.listUricAcid()
				this.queryTrendList()
				this.statisticsExce()
				// this.queryUricAcidCompare()
			},
			formatDate(date) {
				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			listUricAcid() {
				listUricAcid({
					userId: this.userId,
					targetId: this.targetId
				}).then(res => {
					this.records = res.rows || []
					if (this.records.length > 0) {
						const latestRecord = this.records[0]
						console.log(latestRecord)
						
						// 计算尿酸值在0-1200范围内的比例
						const uricAcid = parseFloat(latestRecord.uricAcid) || 0
						const proportion = uricAcid / 1200 // 将尿酸值转换为0-1之间的比例
						
						// 创建新的图表数据对象以确保视图更新
						this.chartData = {
							series: [{
								name: "尿酸值",
								color: latestRecord.color || '#fb3f3f',
								data: proportion
							}]
						}
						
						// 更新opts配置
						this.opts = {
							type: 'arcbar',
							width: 200,
							height: 200,
							background: '#FFFFFF',
							padding: [0, 0, 0, 0],
							dataLabel: true,
							animation: true,
							title: {
								name: this.formatValue(uricAcid),
								fontSize: 20,
								color: '#333333'
							},
							subtitle: {
								name: 'μmol/L',
								fontSize: 12,
								color: '#666666'
							},
							extra: {
								arcbar: {
									type: 'default',
									width: 20,
									backgroundColor: '#E5E5E5',
									startAngle: 0.75,
									endAngle: 0.25,
									radius: 80,
									linearType: 'none',
									roundCap: true
								}
							}
						}
						
						console.log('Updated chart data:', this.chartData)
					}
				})
			},
			queryTrendList() {
				queryTrendListUA({
					userId: this.userId,
					targetId: this.targetId,
					startDate: this.startDate,
					endDate: this.endDate,
					type: this.activeFilter
				}).then(res => {
					if (res.data && res.data.length > 0) {
						// 根据不同类型格式化日期标签
						let categories = []
						if (this.activeFilter === 'week7' || this.activeFilter === 'day') {
							categories = res.data.map(item => {
								const date = new Date(item.measuredTime)
								return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
							})
						} else {
							categories = res.data.map(item => item.measuredTime)
						}
						
						const uricAcidData = res.data.map(item => parseFloat(item.uricAcid))
						
						// 更新trendOpts配置
						this.trendOpts = {
							...this.trendOpts,
							extra: {
								...this.trendOpts.extra,
								tooltip: {
									showBox: true,
									showArrow: true,
									borderWidth: 0,
									borderRadius: 4,
									fontColor: '#FFFFFF',
									formatter: (item, category, index) => {
										// 获取对应的颜色
										const color = res.data[index]?.color || '#4cd8aa'
										// 设置tooltip背景色
										return {
											text: `尿酸值: ${item.data}`,
											color: color,
											bgColor: color
										}
									}
								}
							}
						}
						
						this.trendChartData = {
							categories: categories,
							series: [{
								name: '尿酸值',
								data: uricAcidData
							}]
						}
					} else {
						// 如果没有数据，显示空数据
						this.trendChartData = {
							categories: [],
							series: [{
								name: '尿酸值',
								data: []
							}]
						}
					}
				}).catch(err => {
					console.error('获取趋势数据失败:', err)
				})
			},
			statisticsExce() {
				statisticsExceUA({
					userId: this.userId,
					targetId: this.targetId,
					startDate: this.startDate,
					endDate: this.endDate
				}).then(res => {
					if (res.data) {
						this.statistics.normalCount = res.data.正常 || 0;
						this.statistics.highCount = res.data.高尿酸 || 0;
					}
				})
			},
			// queryUricAcidCompare() {
			// 	queryUricAcidCompare({
			// 		userId: this.userId,
			// 		targetId: this.targetId,
			// 		selectedDate: this.selectedDate,
			// 		compareDate: this.compareDate,
			// 		type: this.comparisonType
			// 	}).then(res => {
			// 		if (res.data) {
			// 			this.comparisonData = res.data
			// 			this.comparisonChartData = {
			// 				categories: res.data.categories || [],
			// 				series: res.data.series || []
			// 			}
			// 		}
			// 	})
			// },
			switchFilter(type) {
				this.activeFilter = type;

				// 设置默认日期范围
				const today = new Date();
				switch (type) {
					case 'week7':
						// 计算7天前的日期
						const sevenDaysAgo = new Date(today);
						sevenDaysAgo.setDate(today.getDate() - 6);
						this.startDate = this.formatDate(sevenDaysAgo);
						this.endDate = this.formatDate(today);
						break;
					case 'day':
						this.startDate = this.formatDate(today);
						this.endDate = this.formatDate(today);
						break;
					case 'week':
						// 计算本周的周一
						const weekMonday = new Date(today);
						weekMonday.setDate(today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1));
						// 计算本周的周日
						const weekSunday = new Date(weekMonday);
						weekSunday.setDate(weekMonday.getDate() + 6);

						this.startDate = this.formatDate(weekMonday);
						this.endDate = this.formatDate(weekSunday);
						break;
					case 'month':
						const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
						this.startDate = this.formatDate(monthStart);
						this.endDate = this.formatDate(today);
						break;
				}

				this.queryTrendList()
				this.statisticsExce()
			},
			switchComparisonType(type) {
				this.comparisonType = type
				this.queryUricAcidCompare()
			},
			onStartDateChange(e) {
				this.startDate = e.detail.value
				this.queryTrendList(this.activeFilter)
				this.statisticsExce()
			},
			onEndDateChange(e) {
				this.endDate = e.detail.value
				this.queryTrendList(this.activeFilter)
				this.statisticsExce()
			},
			onSelectedDateChange(e) {
				this.selectedDate = e.detail.value
				this.queryUricAcidCompare()
			},
			onCompareDateChange(e) {
				this.compareDate = e.detail.value
				this.queryUricAcidCompare()
			},
			toMoreUricAcid() {
				uni.navigateTo({
					url: `/subPackage_1/pages/index/healthData/more-uric-acid?targetId=${this.targetId}`
				})
			},
			addRecord() {
				uni.navigateTo({
					url: `/subPackage_1/pages/index/healthData/add-uric-acid?targetId=${this.targetId}`
				})
			},
			viewAbnormal() {
				// 查看异常记录
				uni.navigateTo({
					url: `/subPackage_1/pages/index/healthData/more-uric-acid?targetId=${this.targetId}&filter=abnormal`
				})
			}
		}
	}
</script>

<style>
	.uric-acid-container {
		min-height: 100vh;
		background: #fff;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
	}

	.section-header text {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}

	.view-more {
		color: #7BC691;
		font-size: 13px;
	}

	.latest-uric-acid {
		padding: 0 15px 20px;
		position: relative;
		overflow: hidden;
	}

	.latest-uric-acid .section-header {
		position: relative;
		overflow: hidden;
	}

	.latest-uric-acid .section-header::after {
		content: '';
		position: absolute;
		top: 26rpx;
		left: 10rpx;
		width: 100%;
		height: 50rpx;
		background-image: url('https://www.ruilongan.com/profile/upload/2025/06/27/路径@2x_20250627113158A059.png');
		background-repeat: no-repeat;
		background-position: left top;
		background-size: contain;
		z-index: 1;
	}

	.latest-uric-acid .section-header text:first-child {
		position: relative;
		z-index: 2;
		font-size: 38rpx;
		font-weight: 500;
		color: #000;
	}

	.latest-uric-acid .section-header .view-more {
		position: relative;
		z-index: 2;
	}

	.charts-box {
		width: 360rpx;
		height: 360rpx;
		margin: 30rpx auto;
	}

	.measure-time {
		text-align: center;
		color: #abaeaf;
		font-size: 13px;
		margin-top: 15px;
		position: relative;
		z-index: 2;
	}

	.uric-acid-trend {
		padding: 24rpx;
	}

	.uric-acid-trend .section-header {
		position: relative;
		overflow: hidden;
	}

	.uric-acid-trend .section-header::after {
		content: '';
		position: absolute;
		top: 26rpx;
		left: 10rpx;
		width: 100%;
		height: 50rpx;
		background-image: url('https://www.ruilongan.com/profile/upload/2025/06/27/路径@2x_20250627113158A059.png');
		background-repeat: no-repeat;
		background-position: left top;
		background-size: contain;
		z-index: 1;
	}

	.uric-acid-trend .section-header text:first-child {
		position: relative;
		z-index: 2;
		font-size: 38rpx;
		font-weight: 500;
		color: #000;
	}

	.uric-acid-trend .section-header .view-more {
		position: relative;
		z-index: 2;
	}

	.date-filter {
		display: flex;
		flex-direction: column;
		padding: 0 15px;
		margin-bottom: 10px;
		border-bottom: 1px solid #f5f5f5;
	}

	.filter-buttons {
		display: flex;
		align-items: center;
		height: 40px;
	}

	.filter-buttons text {
		margin-right: 8px;
		color: #666;
		font-size: 13px;
		padding: 4px 12px;
		border-radius: 15px;
		background-color: #F5F5F5;
	}

	.filter-buttons .active {
		color: #fff;
		background-color: #4CD080;
	}

	.date-picker-range {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 8px 0;
		width: 100%;
	}

	.date-picker-range picker {
		flex: 0 0 auto;
		width: 95px;
	}

	.date-picker-range picker text {
		display: block;
		text-align: center;
		padding: 4px 0;
		font-size: 12px;
		color: #666;
		background: #F5F5F5;
		border-radius: 4px;
	}

	.separator {
		padding: 0 4px;
		color: #666;
		font-size: 12px;
	}

	.chart-container {
		height: 220px;
		padding: 10px;
	}

	.legend {
		display: flex;
		justify-content: center;
		padding: 10px 0;
		border-top: 1px solid #f5f5f5;
		background-color: #FBFBFD;
		border-radius: 8px;
		margin: 0 15px;
	}

	.legend-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 0;
		font-size: 12px;
		color: #666;
		padding: 8px 12px;
		flex: 1;
		position: relative;
	}

	.legend-item:not(:last-child)::after {
		content: '';
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 1px;
		height: 60%;
		background-color: #E0E0E0;
	}

	.legend-label {
		display: flex;
		align-items: center;
		margin-bottom: 4px;
	}

	.count {
		font-size: 11px;
		color: #999;
	}

	.count.normal {
		color: #333;
	}

	.count.high {
		color: #ff8080;
	}

	.count.low {
		color: #1b76ff;
	}

	.dot {
		width: 12px;
		height: 8px;
		border-radius: 2px;
		margin-right: 4px;
	}

	.dot.normal {
		background: #10c558;
	}

	.dot.high {
		background: #ff8080;
	}

	.dot.low {
		background: #1b76ff;
	}

	.view-abnormal {
		text-align: center;
		color: #ff4d4f;
		font-size: 28rpx;
		padding: 20rpx 0;
	}

	.uric-acid-comparison {
		padding: 24rpx;
	}

	.uric-acid-comparison .section-header {
		position: relative;
		overflow: hidden;
	}

	.uric-acid-comparison .section-header::after {
		content: '';
		position: absolute;
		top: 26rpx;
		left: 10rpx;
		width: 100%;
		height: 50rpx;
		background-image: url('https://www.ruilongan.com/profile/upload/2025/06/27/路径@2x_20250627113158A059.png');
		background-repeat: no-repeat;
		background-position: left top;
		background-size: contain;
		z-index: 1;
	}

	.uric-acid-comparison .section-header text:first-child {
		position: relative;
		z-index: 2;
		font-size: 38rpx;
		font-weight: 500;
		color: #000;
	}

	.comparison-tabs {
		display: flex;
		align-items: center;
		padding: 0 15px;
		margin-bottom: 10px;
		height: 40px;
		border-bottom: 1px solid #f5f5f5;
	}

	.comparison-tabs text {
		margin-right: 8px;
		color: #666;
		font-size: 13px;
		padding: 4px 12px;
		border-radius: 15px;
		background-color: #F5F5F5;
	}

	.comparison-tabs .active {
		color: #fff;
		background-color: #4CD080;
	}

	.date-selection {
		padding: 0 30rpx 20rpx;
	}

	.date-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.comparison-result {
		padding: 0 30rpx 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.result-item {
		flex: 1;
		font-size: 24rpx;
		color: #666;
	}

	.result-comparison {
		padding: 10rpx 20rpx;
		background-color: #f0f9ff;
		border-radius: 10rpx;
		margin: 0 20rpx;
	}

	.comparison-value {
		font-size: 28rpx;
		font-weight: 500;
	}

	.comparison-value.up {
		color: #ff4d4f;
	}

	.comparison-value.down {
		color: #4cd964;
	}

	.comparison-chart {
		padding: 0 30rpx 20rpx;
	}

	.data-records {
		padding: 24rpx;
		padding-bottom: 120rpx;
	}

	.data-records .section-header {
		position: relative;
		overflow: hidden;
	}

	.data-records .section-header::after {
		content: '';
		position: absolute;
		top: 26rpx;
		left: 10rpx;
		width: 100%;
		height: 50rpx;
		background-image: url('https://www.ruilongan.com/profile/upload/2025/06/27/路径@2x_20250627113158A059.png');
		background-repeat: no-repeat;
		background-position: left top;
		background-size: contain;
		z-index: 1;
	}

	.data-records .section-header text:first-child {
		position: relative;
		z-index: 2;
		font-size: 38rpx;
		font-weight: 500;
		color: #000;
	}

	.data-records .section-header .view-more {
		position: relative;
		z-index: 2;
	}

	.record-item {
		padding: 15px;
		border-bottom: 1px solid #f5f5f5;
	}

	.record-main {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8px;
		font-size: 14px;
	}

	.record-sub {
		display: flex;
		justify-content: space-between;
		color: #666;
		font-size: 13px;
		margin-bottom: 5px;
	}

	.record-time {
		color: #999;
		font-size: 12px;
	}

	.disclaimer {
		padding: 20rpx 30rpx;
		text-align: center;
		font-size: 24rpx;
		color: #999;
	}

	.bottom-button {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 15px;
		background: #fff;
		box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.bind-device {
		padding-left: 40rpx;
		color: #4CD080;
		font-size: 28rpx;
	}

	.add-record {
		background: #10c558;
		color: #fff;
		border-radius: 10px;
		font-size: 15px;
		height: 44px;
		line-height: 44px;
		border: none;
		width: 430rpx;
		margin: 0;
	}
</style>
